<template lang="pug">
  Card.task-con
    header.task-header
      .task-form
        Form(ref='taskForm',:model='formValidate',:rules="ruleValidate",:label-width="95")
          FormItem(label='任务名称：',prop='taskName')
            Input(v-model="formValidate.taskName",placeholder="任务名称",:maxlength="50")
      .task-btn
        Button(type="error",v-if="$route.query.status==='modify'&&checkOutStatus",:disabled='checkStatus',@click="handleCheckOut") 签出
        Button(type="success",v-if="$route.query.status==='modify'&&checkInStatus",:disabled='!checkStatus || checkUserStatus',@click="handleCheckIn") 签入
        Button(type="primary",v-if="$route.query.status==='add'",@click="handleSave") 保存
        Button(@click="$router.push('/index')") 返回
    section.task-body
      Tabs(v-model='taskPaneActive')
        TabPane(label='基本属性',name='1')
          basicAttr(ref='basicAttr')
        TabPane(label='页面模型',name='2')
          pageModel(ref="pageModel")
</template>

<script>
import asyncGather from '../api'
import basicAttr from './components/TaskBasicAttr'
import pageModel from './components/TaskPageModel'

export default {
  components: { basicAttr, pageModel },
  data() {
    return {
      checkStatus: false,
      checkUserStatus: false,
      checkInStatus: false,
      checkOutStatus: false,
      taskPaneActive: '1',
      formValidate: {
        taskName: ''
      },
      ruleValidate: {
        taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.$nextTick(() => {
      const breadcrumbData = [{ name: '采集中心' }]
      if (this.$route.query.status === 'add') {
        breadcrumbData.push({ name: '新增' })
      } else {
        breadcrumbData.push({ name: '修改' })
      }
      this.$store.dispatch('breadcrumb/getBreadCrumb', breadcrumbData)
      if (this.$route.query.status === 'modify') {
        const taskPower = JSON.parse(sessionStorage.getItem('routes')).filter(item => item.name === 'gather')[0]
        if (taskPower.children[0].meta['/task/checkin']) this.checkInStatus = true
        if (taskPower.children[0].meta['/task/checkout']) this.checkOutStatus = true
        if (this.$route.query.checkType === '0') {
          this.checkStatus = true
          if (this.$route.query.updatePersonId !== sessionStorage.getItem('userId')) this.checkUserStatus = true
        }
        this.handleTaskQuery()
      }
    })
  },
  methods: {
    handleTaskQuery: async function() {
      try {
        const res = JSON.parse(JSON.stringify((await asyncGather.taskQuery({ params: { taskId: this.$route.query.taskId } })).data.data))
        const [pageModelData, basicAttrData] = [{}, {}]
        ;({
          siteId: pageModelData.siteId,
          startUrl: pageModelData.startUrl,
          moreStartUrl: pageModelData.moreStartUrl,
          taskPeriodType: basicAttrData.taskPeriodType,
          charSet: basicAttrData.charSet,
          requestType: basicAttrData.requestType,
          deduplicate: basicAttrData.deduplicate,
          periodicDeduplicate: basicAttrData.periodicDeduplicate,
          maxDeduplicateTime: basicAttrData.maxDeduplicateTime,
          connectionTimeout: basicAttrData.connectionTimeout,
          maxRetryCount: basicAttrData.maxRetryCount,
          proxyId: basicAttrData.proxyId,
          priority: basicAttrData.priority,
          crawlTimeInterval: basicAttrData.crawlTimeInterval,
          taskType: basicAttrData.taskType,
          userAgent: basicAttrData.userAgent,
          referer: basicAttrData.referer,
          startTime: basicAttrData.startTime,
          endTime: basicAttrData.endTime
        } = res)
        this.formValidate.taskName = res.taskName
        this.$refs['basicAttr'].formValidate = basicAttrData
        this.$refs['pageModel'].formValidate = pageModelData
      } catch (error) {}
    },
    handleValidVal() {
      const url = new RegExp(
        '^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
        'i'
      )
      if (this.$refs['basicAttr'].formValidate.startTime === '') {
        this.$Message.warning('请选择采集起始时间')
        this.taskPaneActive = '1'
        return false
      }
      if (this.$refs['basicAttr'].formValidate.endTime === '') {
        this.$Message.warning('请选择采集结束时间')
        this.taskPaneActive = '1'
        return false
      }
      // if (this.$refs['basicAttr'].formValidate.userAgent === '') {
      //   this.$Message.warning('请输入用户代理')
      //   this.taskPaneActive = '1'
      //   return false
      // }
      // if (this.$refs['basicAttr'].formValidate.referer === '') {
      //   this.$Message.warning('请输入referer')
      //   this.taskPaneActive = '1'
      //   return false
      // }
      if (!url.test(this.$refs['basicAttr'].formValidate.referer)) {
        this.$Message.warning('referer格式错误，非正确referer格式')
        this.taskPaneActive = '1'
        return false
      }
      if (this.$refs['basicAttr'].formValidate.endTime < this.$refs['basicAttr'].formValidate.startTime) {
        this.$Message.warning('采集结束时间不得小于采集开始时间')
        this.taskPaneActive = '1'
        return false
      }
      if (this.$refs['pageModel'].formValidate.startUrl === '') {
        this.$Message.warning('请输入页面模型采集起始地址')
        this.taskPaneActive = '2'
        return false
      }
      if (!url.test(this.$refs['pageModel'].formValidate.startUrl)) {
        this.$Message.warning('页面模型采集起始地址格式错误，非正确起始地址')
        this.taskPaneActive = '2'
        return false
      }
      return true
    },
    handleCheckOut: async function() {
      try {
        await asyncGather.checkout({ data: { taskId: this.$route.query.taskId } })
        this.$Message.success('签出成功')
        this.checkStatus = true
      } catch (error) {
        this.checkStatus = false
      }
    },
    handleCheckIn() {
      this.$refs['taskForm'].validate(async valid => {
        if (valid) {
          if (this.handleValidVal()) {
            const taskChildData = Object.assign({ taskName: this.formValidate.taskName }, this.$refs['basicAttr'].formValidate, this.$refs['pageModel'].formValidate, {
              taskId: this.$route.query.taskId,
              status: this.$route.query.status
            })
            try {
              await asyncGather.checkin({ data: taskChildData })
              this.checkStatus = false
              this.$Message.success('签入成功')
              this.$router.push('/index')
            } catch (error) {
              this.checkStatus = true
            }
          }
        }
      })
    },
    handleSave() {
      this.$refs['taskForm'].validate(async valid => {
        if (valid) {
          if (this.handleValidVal()) {
            try {
              await asyncGather.taskadd({
                data: Object.assign({ taskName: this.formValidate.taskName }, this.$refs['basicAttr'].formValidate, this.$refs['pageModel'].formValidate)
              })
              this.$Message.success('任务添加成功')
              this.$router.push('/index')
            } catch (error) {}
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
@import '../index.scss';
</style>
